﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.Foundation.Metadata;
using Windows.UI.Core;
using Windows.UI.Popups;
using System.ServiceModel;

namespace wBudget.Common
{
    class ErrorMessage
    {
        private static bool dialogOpened = false;
        private static Queue<QueueItem> queue = new Queue<QueueItem>(); 

        private class QueueItem
        {
            public string Title
            {
                get;
                set;
            }

            public string Message
            {
                get;
                set;
            }

            internal QueueItem(string title, string message)
            {
                this.Title = title;
                this.Message = message;
            }
        }

        /// <summary>
        /// asynchronous function to display an error-message
        /// </summary>
        /// <param name="title">the title of the message</param>
        /// <param name="message">the message to display</param>
        internal static void Show(string title, string message)
        {
            ShowInternal(title, message, false);
        }

        private static async void ShowInternal(string title, string message, bool keepDialogOpen)
        {
            if (dialogOpened && !keepDialogOpen)
            {
                queue.Enqueue(new QueueItem(title, message));
            }
            else
            {
                dialogOpened = true;
                MessageDialog error = new MessageDialog(message, title);
                await error.ShowAsync();
                if (queue.Count != 0)
                {
                    QueueItem item = queue.Dequeue();
                    ErrorMessage.ShowInternal(item.Title, item.Message, true);
                }
                else
                {
                    dialogOpened = false;
                }
            }
        }
    }
}
